package com.dede.getmusic.module.home

import android.Manifest
import android.app.Activity
import android.content.Context
import android.widget.ImageView
import com.dede.getmusic.base.BasePresenter
import com.dede.getmusic.data.*
import com.dede.getmusic.extends.kson.fromJson
import com.dede.getmusic.extends.post2Rx
import com.dede.getmusic.help.ImageLoadHelper
import com.dede.getmusic.module.download.DownloadServer
import com.dede.getmusic.util.AES
import com.dede.mypermission.MyPermission
import com.lzy.okgo.OkGo
import io.reactivex.Observable
import org.jetbrains.anko.defaultSharedPreferences
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.startService
import org.jetbrains.anko.uiThread

/**
 * @author hsh
 * @date 2017/10/12 14:26.
 * @doc
 */
class MainPresenter(private val view: IMainView) : BasePresenter(view) {

    /**
     * 搜索音乐
     */
    fun searchMusic(text: String = this.text) {
        this.text = text
        if (checkText()) return
        this.offset = 0
        loadMusic().subscribe({
            view.refreshMusicFinish(text, it.songs, it.songCount > 20)
        }) {
            view.error("网络错误")
            it.printStackTrace()
        }

        view.refreshSearchHis(insertSearchHis(text))
    }

    private var offset = 0//偏移量
    private var text = ""

    private fun loadMusic(): Observable<SearchInfo> {
        return OkGo.post<String>("http://music.163.com/api/search/get/web")
                .tag(view)
                .params("type", "1")
                .params("limit", "20")
                .params("offset", offset.toString())
                .params("s", text)
                .post2Rx()
                .map { BaseResult(it.body()) }
                .filter {
                    if (!it.status)
                        view.error("网络错误")
                    it.status
                }
                .map { it.result.fromJson<SearchInfo>() }
    }

    fun loadImg(img: ImageView) {
        doAsync {
            val bitmap = ImageLoadHelper.loadImage(view.context(), "http://bing.ioliu.cn/v1?d=0&w=1080")
            uiThread {
                img.setImageBitmap(bitmap)
            }
        }
//      https://api.dujin.org/bing/1366.php
//        OkGo.get<Bitmap>("http://bing.ioliu.cn/v1?d=0&w=1080")
//                .tag(view)
//                .converter(BitmapConvert())
//                .adapt(ObservableResponse<Bitmap>())
//                .rxScheduler()
//                .subscribe({
//                    img.setImageBitmap(it.body())
//                }) { it.printStackTrace() }
    }

    /**
     * 搜索列表加载更多
     */
    fun loadMoreMusic() {
        if (checkText()) return
        this.offset += 20
        loadMusic().subscribe({
            view.loadMoreMusicFinish(it.songs, it.songs.size == 20 && it.songCount > offset + 20)
        }) {
            view.error("网络错误", true)
            it.printStackTrace()
        }
    }

    private fun checkText(): Boolean {
        if (text.isBlank()) {
            view.error("请输入关键字")
            return true
        }
        return false
    }

    var songFileInfo: SongFileInfo? = null

    /**
     * 加载音乐链接
     */
    fun loadMusicLink(songsBean: SearchInfo.SongsBean, download: Boolean = false) {
        OkGo.post<String>(AES.createRequestLink(songsBean.id.toString()))
                .tag(view)
                .post2Rx()
                .map { BaseData(it.body()) }
                .map { it.data.fromJson<ArrayList<SongLinkInfo>>() }
                .filter { it.isNotEmpty() }
                .map { it[0] }
                .subscribe({ songInfo ->
                    songFileInfo = SongFileInfo.createSongFileInfo(songsBean, songInfo)
                    if (download) {
                        download(songFileInfo!!)
                    } else {
                        view.loadMusicLinkFinish(songInfo.url)
                    }
                }) {
                    toast("网络错误")
                    it.printStackTrace()
                }
    }

    /**
     * 下载文件
     */
    fun downloadMusic(songsBean: SearchInfo.SongsBean) {
        if (songFileInfo == null || songsBean.id != songFileInfo!!.id) {
            loadMusicLink(songsBean, true)
        } else {
            download(songFileInfo!!)
        }
    }

    private fun download(songFileInfo: SongFileInfo) {
        (view as Context).startService<DownloadServer>("info" to songFileInfo)
    }

    fun requestPer(activity: Activity) {
        MyPermission.with(activity)
                .permission(Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .onDenied { toast("申请读写存储权限失败") }
                .request()
    }

    private val sp by lazy { view.context().defaultSharedPreferences }

    fun getSearchList(): MutableList<String> {
        return sp.getString("search_his", "")
                .split(",")
                .filter { it.isNotBlank() }
                .toMutableList()
    }

    fun insertSearchHis(his: String): MutableList<String> {
        val searchList = getSearchList()
        val indexOf = searchList.indexOf(his)
        if (indexOf != -1) {
            searchList.removeAt(indexOf)
        }
        searchList.add(0, his)
        while (searchList.size > 10) {
            searchList.removeAt(searchList.size - 1)
        }
        val builder = StringBuilder()
        searchList.forEach {
            builder.append(it)
            builder.append(",")
        }
        sp.edit().putString("search_his", builder.toString()).apply()
        return searchList
    }

    fun clearSearchHis() {
        sp.edit().remove("search_his").apply()
        view.refreshSearchHis(emptyList())
    }

    fun removeSearchHis(his: String) {
        val searchList = getSearchList()
        searchList.remove(his)
        val builder = StringBuilder()
        searchList.forEach {
            builder.append(it)
            builder.append(",")
        }
        sp.edit().putString("search_his", builder.toString()).apply()
    }
}